package com.netty.pro.netty.nio;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author xuzn
 * @ClassName: NioFileChannel001
 * @ProjectName echo-project
 * @date 2020/3/4/21:01
 */
public class NioFileChannel001 {
  public static void main(String[] args) throws Exception {
    String str = "hello channel";
    // 输出流
    FileOutputStream fileOutputStream = new FileOutputStream("d:\\filechannel01.txt");
    // 通过fileOutputStream获取对应的channel
    // 这个fileChannel的真实类型是FileChannelImpl
    FileChannel fileChannel = fileOutputStream.getChannel();
    // 创建一个缓冲区
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    // 将str放入缓冲区
    byteBuffer.put(str.getBytes());
    // 将byteBuffer进行flip操作,因为这个缓冲区可读可写,读到缓冲区后就要写入到channel,通过flip进行读写转换
    byteBuffer.flip();
    fileChannel.write(byteBuffer);
    fileOutputStream.close();
  }
}
